package com.project.util;

import com.project.service.Servlet;

import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * Service工厂类
 */
public class ServiceFactory {
    /**
     * 单例模式
     */
    private static Properties pro = new Properties();
        private static Map<String,Servlet> servletMap = new HashMap<>();
    static {
        try {
            pro.load(new FileReader("web.txt"));
            //得到属性文件的键集合
            Set<String> keySet = pro.stringPropertyNames();
//            遍历获取键 模板
            for (String key : keySet){
            //根据键获得值
                String classPath = pro.getProperty(key);
//                加载类，获得模板
                Class c = Class.forName(classPath);
//               将键和模板放入集合
                servletMap.put(key,(Servlet)c.getConstructor().newInstance());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Servlet getServlet(String url){
       return servletMap.get(url);
    }

//    public static void main(String[] args)  {
//        Servlet s1 = ServiceFactory.getServlet("lang");
//        Servlet s2 = ServiceFactory.getServlet("lang");
//        System.out.println(s1==s2);
//    }
}
